package pack0923;

import java.util.Arrays;
import java.util.Scanner;

// 数组查找方式
public class DemoG {

    // 顺序（线性）查找法
    public static void a() {
        int len = (int) (Math.random() * 21 + 10);
        int[] array = new int[len];
        for (int i = 0; i < len; i++) {
            array[i] = (int) (Math.random() * 100 + 1);
        }
        // 输出数组
        System.out.println(Arrays.toString(array));
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        boolean flag = false;
        for (int i = 0; i < array.length; i++) {
            if (num == array[i]) {
                flag = true;
                break;
            }
        }
        System.out.println(flag ? "存在" : "不存在");
    }

    // 二分查找法
    public static void b() {
        int len = (int) (Math.random() * 21 + 10);
        int[] array = new int[len];
        for (int i = 0; i < len; i++) {
            array[i] = (int) (Math.random() * 100 + 1);
        }
        // 输出数组
        System.out.println(Arrays.toString(array));
        Scanner scan = new Scanner(System.in);
        // 要查找的数
        int num = scan.nextInt();
        // 排序:冒泡排序法
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
        // 找到这个数在数组中是否存在
        int begin = 0;
        int end = len - 1;
        int middle = (begin + end) / 2;
        // 判断首尾
        if (num == array[begin] || num == array[end]) {
            System.out.println("恭喜你，找到了！");
            return;
        }
        while (begin < end - 1) {
            if (num > array[middle]) {
                begin = middle;
                middle = (begin + end) / 2;
            } else if (num < array[middle]) {
                end = middle;
                middle = (begin + end) / 2;
            } else {
                System.out.println("恭喜你，找到了！");
                return;
            }
        }
        System.out.println("没有找到！");
    }

    public static void main(String[] args) {
        b();
    }
}